<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/manage' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统权限</el-breadcrumb-item>
      <el-breadcrumb-item>权限集</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="w">
      <el-button @click="addFirstPer" type="primary" size="mini" plain style="margin-bottom: 10px;font-weight: 800;"><i class="el-icon-circle-plus-outline" style="margin-right: 8px;"></i>添加权限集</el-button>
      <el-button v-show="updateBtn" size="mini" @click="subUpdates">保存修改</el-button>
      <el-tree
        :data="resTreeData"
        empty-text="暂无数据"
        :props="defaultTreeData"
        :expand-on-click-node="false"
        default-expand-all
        node-key="id"
        ref="tree">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span v-if="node.level===1">
            <el-button type="text" size="mini" @click="updateSet(node, data)"><i class="el-icon-edit"></i>修改</el-button>
            <el-button type="text" size="mini" @click="() => append(node, data)">
              <i class="el-icon-circle-plus"></i>添加/删除
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <el-dialog
      title="权限集新增权限"
      :visible.sync="updateDialogVisible"
      width="45%"
      center
      @closed="dialogClose">
      <el-transfer
        :data="transferData"
        v-model="havePri"
        :titles="['待添加权限', '已有权限']"
        @change="dialogDataChange">
      </el-transfer>
      <div class="transfer-right-footer" v-if="transferChangeVisible">
        <el-button type="primary" size="mini" plain @click="transferSub">保存</el-button>
        <el-button type="info" size="mini" plain @click="transferReset">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="新增权限集"
      :visible.sync="addDialogVisible"
      width="45%"
      center>
      <el-form :model="addForm" ref="addForm">
        <el-form-item label="权限集名" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="权限集描述" prop="description">
          <el-input v-model="addForm.description" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div class="btn">
        <el-button size="small" @click="subAdd">提交</el-button>
        <el-button size="small" @click="subAddNext">继续添加</el-button>
      </div>
      <div v-for="param in params" :key="param.name">
        <span>权限集名称：{{param.name}}</span>
        <span>权限集描述：{{param.description}}</span>
      </div>
    </el-dialog>
    <el-dialog
      title="修改权限集"
      :visible.sync="updatePriDialogVisible"
      width="45%"
      center>
      <el-form :model="updateForm" ref="updateForm">
        <el-form-item label="权限集名" prop="name">
          <el-input v-model="updateForm.name" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="权限集描述" prop="description">
          <el-input v-model="updateForm.description" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div class="btn">
        <el-button size="small" @click="updateBtnSub">确定</el-button>
        <el-button size="small" @click="updateBtnReset">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'permission-set',
  data () {
    return {
      resTreeData: [],
      defaultTreeData: {
        label: 'name',
        children: 'children'
      },
      transferData: [],
      havePri: [],
      updateDialogVisible: false,
      transferChangeVisible: false,
      addDialogVisible: false,
      updatePriDialogVisible: false,
      updateBtn: false,
      updateForm: {
        name: '',
        description: '',
        setId: 0
      },
      addForm: {
        name: '',
        description: ''
      },
      params: [],
      adds: [],
      removes: [],
      pid: 0,
      updates: [],
      oldData: {},
      activeNode: {}
    }
  },
  methods: {
    addFirstPer () {
      this.addDialogVisible = true
    },
    append (node, data) {
      this.pid = data.id
      // 后台返回已有权限，没有权限，前端合并作为数据源，判断已有权限添加到数组havePer中显示在右边
      this.$ajax.post('/admin/manager/permission/set/relation/detail', JSON.stringify(data.id)).then((res) => {
        res.data.data.hadList.forEach((item, index) => {
          this.havePri.push(item.id)
        })
        res.data.data.selectableList.push(...(res.data.data.hadList))
        res.data.data.selectableList.forEach((item, index) => {
          this.transferData.push({
            key: item.id,
            label: item.name
          })
        })
      })
      // 显示穿梭框
      this.updateDialogVisible = true
    },
    updateSet (node, data) {
      this.activeNode = node
      this.updatePriDialogVisible = true
      this.updateForm.name = data.name
      this.updateForm.description = data.description
      this.updateForm.setId = data.id
      this.oldData = JSON.parse(JSON.stringify(this.updateForm))
    },
    updateBtnSub () {
      let isUpdate = (this.oldData.name !== this.updateForm.name || this.oldData.description !== this.updateForm.description)
      if (!this.updateBtn && isUpdate) {
        this.updateBtn = true
      }
      if (isUpdate) {
        this.updates.forEach((item, index) => {
          if (item.id === this.updateForm.setId) {
            this.updates.splice(index, 1)
          }
        })
        this.updates.push({
          id: this.updateForm.setId,
          name: this.updateForm.name,
          description: this.updateForm.description
        })
        this.activeNode.data.name = this.updateForm.name
      }
      this.updatePriDialogVisible = false
    },
    updateBtnReset () {
      this.updatePriDialogVisible = false
    },
    subUpdates () {
      let _self = this
      this.$ajax.post('/admin/manager/permission/set/update', JSON.stringify(this.updates)).then((res) => {
        if (res.data.success) {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          _self.updateBtn = false
        }
      })
    },
    dialogDataChange (value, direction, movedKeys) {
      if (!this.transferChangeVisible) {
        this.transferChangeVisible = true
      }
      if (direction === 'right') {
        this.adds.push(...(movedKeys))
      } else if (direction === 'left') {
        this.removes.push(...(movedKeys))
      }
      // 保存用户添加的权限，就是右边穿梭框的数据 value
    },
    dialogClose () {
      // 重置穿梭框数据，再次点击再赋值
      this.transferData = []
      this.pid = 0
      this.adds = []
      this.removes = []
    },
    subAdd () {
      if (this.addForm.name !== '') {
        this.params.push({
          name: this.addForm.name,
          description: this.addForm.description === '' ? '无' : this.addForm.description
        })
      }
      this.$ajax.post('/admin/manager/permission/set/add', JSON.stringify(this.params)).then((res) => {
        if (res.data.success) {
          this.$message({
            type: 'success',
            message: '添加成功'
          })
          this.loadMore()
          this.addDialogVisible = false
        }
      }).then((err) => {
        console.log(err)
      })
    },
    subAddNext () {
      if (this.addForm.name === '') {
        return
      }
      if (this.addForm.description === '') {
        this.addForm.description = '无'
      }
      let param = JSON.stringify(this.addForm)
      this.params.push(JSON.parse(param))
      this.$refs.addForm.resetFields()
    },
    transferSub () {
      let params = {
        setId: this.pid,
        adds: this.adds,
        removes: this.removes
      }
      let _self = this
      this.$ajax.post('/admin/manager/permission/set/relation/change', JSON.stringify(params)).then((res) => {
        if (res.data.success) {
          // 提示，刷新
          this.$message({
            message: '添加成功',
            type: 'success',
            onClose () {
              _self.loadMore()
              _self.updateDialogVisible = false
            },
            duration: 500
          })
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    transferReset () {
      this.updateDialogVisible = false
    },
    loadMore () {
      this.$ajax.post('/admin/manager/permission/matrix/set/list').then((res) => {
        let sets = []
        res.data.data.sets.forEach((item, index) => {
          sets[item.id] = item
          sets[item.id].children = []
        })
        res.data.data.childrens.forEach((item, index) => {
          if (sets[item.permissionSetId]) {
            sets[item.permissionSetId].children.push(item)
          }
        })
        for (let i = 0; i < sets.length; i++) {
          if (typeof sets[i] === 'undefined') {
            sets.splice(i, 1)
            i--
          }
        }
        this.resTreeData = sets
      })
    }
  },
  created () {
    this.loadMore()
  }
}
</script>

<style scoped>
.custom-tree-node{
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.dangerDelete{
  color: #F56C6C;
}
.el-transfer{
  text-align: center;
}
.transfer-right-footer{
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin-top: 10px;
}
  .btn{
    text-align: right;
  }
</style>
